<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="班次名称" prop="classesName">
            <el-input v-model="form.classesName" placeholder="请输入班次名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="班次类型" prop="classesType">
            <el-select class="w100" clearable placeholder="请输入班次类型" v-model="form.classesType">
              <el-option :key="item.value" :label="item.label" :value="item.value" v-for="item in classes_type">
                {{ item.label }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="是否轮班" prop="isShift">
            <el-select class="w100" clearable placeholder="请选择是否轮班" v-model="form.isShift"
              @change="isShiftChange(form.isShift)">
              <el-option :key="item.value" :label="item.label" :value="item.value" v-for="item in isShifts">
                {{ item.label }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="轮班间隔(天)" label-width="100px" prop="shiftInterval">
            <el-input :disabled="form.isShift == '0'" type="number" v-model="form.shiftInterval"
              placeholder="请输入轮班间隔" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="休息规则" prop="restId">
            <!-- <el-input v-model="form.restId" placeholder="请输入休息规则" /> -->
            <el-select class="w100" clearable placeholder="请选择休息规则" v-model="form.restId"
              @change="isShiftChange(form.restId)">
              <el-option :key="item.id" :label="item.remark" :value="item.id" v-for="item in restIdS">
                {{ item.remark }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="每班天数(天)" label-width="100px" prop="numberOfDay">
            <el-input type="number" v-model="form.numberOfDay" placeholder="请输入每班天数" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-divider content-position="center">班组(子)信息</el-divider>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddOrderItem">添加班组</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteOrderItem">删除班组</el-button>
            </el-col>
          </el-row>
          <el-table ref="OrderItem" :data="classesList" :row-class-name="rowOrderItemIndex" tooltip-effect="dark"
            style="width: 100%" @selection-change="handleOrderItemSelectionChange">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column label="班组名称" prop="groupName">
              <template #default="scope">
                <el-input v-model="scope.row.groupName" placeholder="请输入班组名称" />
              </template>
            </el-table-column>
          </el-table>


          <el-row :gutter="10" class="mb8" style="margin-top: 20px;">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddOrderRuleItem">添加规则</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini"
                @click="handleDeleteOrderRuleItem">删除规则</el-button>
            </el-col>
          </el-row>
          <el-table ref="OrderItem" :data="rulesList" :row-class-name="rowOrderItemIndex" tooltip-effect="dark"
            style="width: 100%" @selection-change="handleOrderItemSelectionChange">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column label="起始规则" prop="startRuleId">
              <template #default="scope">
                <el-select v-model="scope.row.id" clearable placeholder="请选择起始规则">
                  <el-option v-for="item in startRuleIdList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="ClassesInformationDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/personnel/classesInformation'
import { dropbox, getRestId } from '/@/api/personnel/classesRules'
import { rule } from '/@/utils/validate';
const emit = defineEmits(['refresh']);
const { classes_type } = useDict('classes_type');

const classesList = ref([]);
const rulesList = ref([]);
const startRuleIdList = ref([]);
const restIdS = ref([]);
const startShiftings = ref([{
  value: -1,
  label: "前一天"
}, {
  value: 0,
  label: "今天"
}, {
  value: 1,
  label: "后一天"
}]);
const checkedOrderItem = ref([]);
// 定义变量内容
const dataFormRef = ref();
const isShifts = ref([{
  value: "0",
  label: "否"
}, {
  value: "1",
  label: "是"
}]);
const visible = ref(false)
const loading = ref(false)
// 定义字典

// 提交表单数据
const form = reactive({
  id: '',
  classesName: '',
  classesType: '',
  shiftInterval: '',
  numberOfDay: '',
  restId: '',
  isShift: '',
  remark: '',
  groups: [],
  rules: []

});

// 定义校验规则
const dataRules = ref({
})

const isShiftChange = (value) => {
  console.log('value', value);

  if (value == 0) {
    form.shiftInterval = ''
  }
}

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  classesList.value = []
  rulesList.value = []
  form.id = ''
  startRuleIdLists(id)
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });
  getRestIdS()
  // 获取classesInformation信息
  if (id) {
    form.id = id
    getclassesInformationData(id)
  }
};
const changeVal = () => {
  startRuleIdList.value = []

}
const getRestIdS = () => {
  getRestId().then((response) => {

    restIdS.value = response.data.records
  })
}

const startRuleIdLists = (id) => {
  dropbox({
    classesId: id
  }).then((response) => {
    let searchData = response.data
    console.log('searchData', searchData);

    startRuleIdList.value = searchData.map((item: any) => {
      return { value: item.id, label: `${item.ruleName}` }
    })
  })
}

/** (子)序号 */
const rowOrderItemIndex = ({ row, rowIndex }) => {
  row.index = rowIndex + 1
}
/** 单选框选中数据 */
const handleOrderItemSelectionChange = (selection: any) => {
  checkedOrderItem.value = selection
}
/** (子)添加按钮操作 */
const handleAddOrderItem = () => {
  let obj = {
    groupName: '',
    // startRuleId: 1,
    // startShifting: 0
  }

  classesList.value.push(obj)
}
/** (子)添加按钮操作 */
const handleAddOrderRuleItem = () => {
  let obj = {
    // groupName: '',
    id: '',
    // startShifting: 0
  }

  rulesList.value.push(obj)
}
/** 预约(子)删除按钮操作 */
const handleDeleteOrderItem = () => {
  if (checkedOrderItem.value.length == 0) {
    // .alert('请先选择要删除(子)数据', '提示', {
    //   confirmButtonText: '确定'
    // })
  } else {
    checkedOrderItem.value.forEach((item: { index: any; }) => {
      for (let i = 0; i < classesList.value.length; i++) {
        if (classesList.value[i].index === item.index) {
          classesList.value.splice(i, 1)
          break
        }
      }
    })
    checkedOrderItem.value = []
  }
}
/** 预约(子)删除按钮操作 */
const handleDeleteOrderRuleItem = () => {
  if (checkedOrderItem.value.length == 0) {
    // .alert('请先选择要删除(子)数据', '提示', {
    //   confirmButtonText: '确定'
    // })
  } else {
    checkedOrderItem.value.forEach((item: { index: any; }) => {
      for (let i = 0; i < rulesList.value.length; i++) {
        if (rulesList.value[i].index === item.index) {
          rulesList.value.splice(i, 1)
          break
        }
      }
    })
    checkedOrderItem.value = []
  }
}

// 提交
const onSubmit = async () => {
  if (classesList.value.length == 0) {
    useMessage().error('班组不能为空！');
    return
  }
  if (rulesList.value.length == 0) {
    useMessage().error('规则不能为空！');
    return
  }
  if (form.isShift == '0') {
    form.shiftInterval = ''
  }
  form.groups = classesList.value
  form.rules = rulesList.value

  const valid = await dataFormRef.value.validate().catch(() => { });
  if (!valid) return false;

  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getclassesInformationData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    if (res.data.groups != null) {
      classesList.value = res.data.groups
    } else {
      classesList.value = []
    }
    if (res.data.rules != null) {
      rulesList.value = res.data.rules
    } else {
      rulesList.value = []
    }
    Object.assign(form, res.data)
  }).finally(() => {
    loading.value = false
  })
};

// 暴露变量
defineExpose({
  openDialog
});
</script>